package servlet;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Account;
import model.Connect;
import model.SQLModel;
import model.UserInfo;
import model.table.DMLTableInterface;
import model.table.ItemTable;

/**
 * Servlet implementation class ServletLogin
 */
public class DMLItemTable extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DMLItemTable() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		try {

			if (request.getMethod().equalsIgnoreCase("post")
					|| request.getMethod().equalsIgnoreCase("get")) {
				try {
					Connect connect = new Connect();
					Account account = connect.checkSession(request, response);
					connect.setSID(connect.getdbSession(request));
					connect.setUser(account.strUserName);
					connect.setPassword(account.strPass);
					Connection conn = connect.simple_connect();
					DMLTableInterface db = new ItemTable(conn);
					String owner = request.getParameter("owner");
					if ("insert".equalsIgnoreCase(request
							.getParameter("mode")))
						db.insert();

					else if ("update".equalsIgnoreCase(request
							.getParameter("mode")))
						db.update();

					else
						db.delete();
					response.sendRedirect("./ViewItemTable?owner=" + owner);

					conn.close();

				} catch (Exception e) {
					System.out.print("Connection unsuccessfly "
							+ e.getMessage());
					// response.sendRedirect("ManageAccount/Login.jsp");
				}
			}

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
